<template>
  <div>
    <div class="steps">
      <el-steps :active="activeIndex" finish-status="success" simple>
        <el-step title="询报价信息" />
        <el-step title="定标信息" />
      </el-steps>
    </div>
    <el-card class="basic-info">
      <el-row slot="header" type="flex" justify="space-between" align="middle">
        <span>定标商品信息</span>
        <div class="operating-area">
          <div class="urgent-order">
            <el-checkbox v-model="emergencyOrder">紧急订货</el-checkbox>
          </div>
          <el-button size="mini" @click="handleSkuAccess" :loading="accessLoading">潜在商品准入</el-button>
          <el-button size="mini" @click="handleUpdateImgInfo" :loading="updateImgLoading">完善图文信息</el-button>
          <el-button v-if="isReject" size="mini" @click="handleRelatedSku">关联商品</el-button>
          <el-button v-if="isReject" size="mini" @click="handleReinquiry" :loading="reinquiryLoading">重新报价</el-button>
          <el-button v-if="!isReject" size="mini" @click="handleBackQuotePage">重新询价</el-button>
          <el-button size="mini" type="primary" :loading="submitLoading" @click="handleCompleteCalibration">定标完成</el-button>
        </div>
      </el-row>
      <BasicTable
        ref="multipleTable"
        show-select-col
        :show-pagination="false"
        :show-ActionCol="false"
        :show-total="false"
        :rowHeight="43"
        :tableMaxHeight="600"
        :loading="tableInfo.loading"
        :data-source="tableInfo.list"
        :columns="tableInfo.columns"
        :selection-change="handleSelect"
        @handleRowChange="handleRowChange"
        showSummary
        :summaryMethod="summaryMethod"
      >
        <el-row
          type="flex"
          justify="space-between"
          align="middle"
          slot="content_context"
          class="table-header"
        >
          <div>
            <el-input
              size="mini"
              v-model="priceExpType"
              placeholder="批量维护成本差异比例超10%备注"
            />
            <el-button
              type="primary"
              size="mini"
              @click="handleBatchUpdateReson"
            >确定</el-button>
          </div>
          <div v-if="recordInfo.settleTypeStr">
            <span>客户支付方式: {{recordInfo.settleTypeStr}}</span>
          </div>
        </el-row>
      </BasicTable>
    </el-card>
    <NotWinSupplierDialog
      :submitLoading="submitLoading"
      :dialog-visible="notWinSupplierDiaVisible"
      @hide-handler="handleCloseNotWinSupplier"
      @confirm-submit="completeCalStepThird"
    />
    <!-- 关联推荐商品 -->
    <RecommendGoods
      :visible.sync="goodsVisible"
      :sourceBillId="sourcingBillId"
      @confirm="queryCalibrationInfo"
    />
    <!-- 无销售区域商品 -->
    <SaleAreaTip
      :visible.sync="tipVisible"
      :skuList="noSaleAreaSkuList"
    />
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import BasicTable from '@/pages/sourcing/components/BasicList';
import NotWinSupplierDialog from '../components/NotWinSupplierDialog'
import RecommendGoods from '../components/RecommendGoods'
import SaleAreaTip from '@sourcing/components/SaleAreaTip'
import { toFixedCustomize, handleOpenNewPage } from '@/utils/bizUtils'
import { summaryMethod } from '../../utils';
import {
  queryCalibrationInfoService,
  calibrationStep1Service,
  calibrationStep2Service,
  calibrationStep3Service,
  turnIntoPotentialService, // 转潜在
  updateImgInfoService, // 完善图文信息
  updateSkuCodeService,
  reinquiryService,
  computeFactoryDirectService
} from '@/api/sourcing/purchaseDetail'
import {
  TABLE_COLUMNS,
  TABLE_COLUMNS2,
  TABLE_COLUMNS3,
  TABLE_COLUMNS3_PROPS,
  FACTORY_DIRECT_OPTIONS,
} from './constants'

export default {
  name: 'OrderCalibration',
  components: {
    BasicTable,
    NotWinSupplierDialog,
    RecommendGoods,
    SaleAreaTip
  },
  data () {
    return {
      recordInfo: {
        settleTypeStr: '',
        settleType: '',
        cityCode: '',
        afreshBill: '', // 是否重新询价 0 否 1 是
      },
      factoryDirect: '',
      FACTORY_DIRECT_OPTIONS,
      tipVisible: false,
      noSaleAreaSkuList: [],
      sourcingBillId: '',
      isDemand: false,
      reinquiryLoading: false,
      priceExpType: '',
      tableInfo: {
        list: [],
        columns: [],
        selection: [],
        loading: false
      },
      accessLoading: false,
      updateImgLoading: false,
      submitLoading: false,
      activeIndex: 1,
      notWinSupplierDiaVisible: false,
      goodsVisible: false,
      emergencyOrder: false,
      submitDataForAllStep: {},
    };
  },
  computed: {
    isReject () {
      const { isReject = false } = this.$route.query;
      return isReject;
    },
    // 是否重新询价
    isReinquiry () {
      const { afreshBill, settleType } = this.recordInfo;
      return afreshBill == 1 || settleType == 4; // 货到付款
    },
  },
  created () {
    const {
      sourcingBillId,
      isDemand = false
    } = JSON.parse(sessionStorage.getItem('detailInfo'));
    this.sourcingBillId = sourcingBillId
    this.isDemand = isDemand
    this.queryCalibrationInfo()
  },

  methods: {
    summaryMethod,
    ...mapMutations('sourcing/purchaseDetail', ['SET_CALIBRATION_STEP_ONE_INFO']),
    // 计算是否厂直
    async computeFactoryDirect (params) {
      const res = await computeFactoryDirectService(
        params,
        state => { this.tableInfo.loading = state })
      if (res) {
        return res.data;
      }
    },
    // 重新报价
    async handleReinquiry () {
      const res = await reinquiryService({ sourcingBillId: this.sourcingBillId }, state => { this.reinquiryLoading = state })
      if (res) {
        const detailInfo = { pageType: 2, isEdit: true, sourcingBillId: this.sourcingBillId }
        sessionStorage.setItem('detailInfo', JSON.stringify(detailInfo));
        this.$router.push({ name: 'purchaseDetail' })
      }
    },
    // 维护图文信息
    async handleUpdateImgInfo () {
      const res = await updateImgInfoService({ sourcingBillId: this.sourcingBillId }, state => { this.updateImgLoading = state })
      if (res) {
        const { data } = res;
        localStorage.setItem('sourcing_bid_skus', JSON.stringify(data))
        handleOpenNewPage(this, { name: 'calibratePerfectGraphics' });
      }
    },
    // 商品准入 线索转潜在
    async handleSkuAccess () {
      const res = await turnIntoPotentialService({ sourcingBillId: this.sourcingBillId }, state => { this.accessLoading = state })
      if (res) {
        const { checkType, data, msg } = res.data;
        // 201 线索商品为一物多码商品（确认的话调用指定接口：）
        // 202 存在线索商品已转潜在的情况
        if (checkType == 201) {
          this.$confirm(`${msg}`, '提示', {
            type: 'warning',
          }).then(() => {
            this.handleUpdateSkuCode()
          }).catch(() => {})
        } else if (checkType == 202) {
          if (data) {
            if (msg) {
              this.handleAlert({
                msg,
                callbackFn: () => { this.toLatentProductAdd(data) }
              })
            } else {
              this.toLatentProductAdd(data)
            }
          } else {
            this.handleAlert({
              msg: msg || '潜在商品准入异常',
              callbackFn: () => { this.queryCalibrationInfo() }
            })
          }
        }
      }
    },
    // alert
    handleAlert ({ msg, callbackFn }) {
      this.$alert(`${msg}`, '提示', {
        confirmButtonText: '确定',
        showClose: false,
        callback: () => {
          callbackFn()
        }
      });
    },
    // 跳转到线索转潜在页面
    toLatentProductAdd (data) {
      this.$router.push({ name: 'latentProductAdd', query: { orderInquiryNo: data } })
    },
    // 线索商品为一物多码商品
    async handleUpdateSkuCode () {
      const res = await updateSkuCodeService({ sourcingBillId: this.sourcingBillId }, state => { this.tableLoading = state })
      if (res) {
        // data 是否返回报价详情
        const { data } = res;
        if (data) {
          this.handleBackQuotePage()
        }
      }
    },
    // 关联商品
    handleRelatedSku () {
      this.goodsVisible = true;
    },
    // 批量维护异常原因
    handleBatchUpdateReson () {
      if (this.tableInfo.selection.length == 0) {
        return this.$message.warning('请勾选商品')
      }
      const skuIds = this.tableInfo.selection.map(item => item.skuCode)
      this.tableInfo.list.forEach(item => {
        if (skuIds.includes(item.skuCode)) {
          Object.keys(item).forEach(ele => {
            if (ele.includes('costDiffScale') && (item[ele] >= 10 || item[ele] <= -10)) {
              const tag = ele.split('_')[1]
              item[`costDiffExceedTenRemark_${tag}`] = this.priceExpType
            }
          })
        }
      })
    },
    // 初始化表头
    initTableColumns () {
      this.tableInfo.columns = _.cloneDeep(TABLE_COLUMNS)
    },
    // 初始化表格数据
    initTableData (skuList) {
      this.tableInfo.list = [];
      this.initTableColumns();
      skuList.forEach((ele, oneIndex) => {
        const curRow = {
          ...ele
        };
        ele.supplierList.forEach((item, index) => {
          this.pushItem(oneIndex, curRow, item, index);
        });
        this.tableInfo.list.push(curRow);
      });
      this.tableInfo.columns = this.tableInfo.columns.concat(TABLE_COLUMNS2);
    },
    pushItem (oneIndex, curRow, item) {
      // 将行内动态列的信息，平铺到行
      const tag = item.supplierCode;
      TABLE_COLUMNS3_PROPS.forEach(name => {
        curRow[`${name}_${tag}`] = item[name];
      });
      curRow[`unitPrice_${tag}`] = item.unitPrice;
      curRow[`factoryDirectCanUpdate_${tag}`] = item.factoryDirectCanUpdate;
      curRow[`canEditBySkuNum_${tag}`] = item.canEditBySkuNum || true;
      // 表头，遍历第1行的动态列时，才追加到表头
      if (oneIndex === 0) {
        const children = _.cloneDeep(TABLE_COLUMNS3)
        children.forEach(i => {
          i.prop = `${i.prop}_${tag}`
          if (i.prop.includes('costDiffScale')) {
            i.render = (h, { row }) => {
              if ((row[i.prop] >= 10 || row[i.prop] <= -10)) {
                return <span style="color: red;">{row[i.prop]}</span>
              }
              return <span>{row[i.prop]}</span>
            }
          }
          if (i.prop.includes('invoiceTypeStr')) {
            i.render = (h, { row }) => {
              if (row[i.prop] == '无税票') {
                return <span style="color: red;">{row[i.prop]}</span>
              }
              return <span>{row[i.prop]}</span>
            }
          }
          if (i.prop.includes('skuNum')) {
            i.render = (h, { row }) => {
              if (row[`costPrice_${tag}`] == null) {
                return <span>{ row[`skuNum_${tag}`] }</span>
              }
              return <el-input-number
                class={ row[`skuNum_${tag}`] ? 'active' : '' }
                size="mini"
                controls={false}
                v-model={row[`skuNum_${tag}`]}
                onChange={val => { this.handleRowChange({ prop: `skuNum_${tag}`, row, val }) }}
              />
            }
          }
          if (i.prop.includes('remark')) {
            i.render = (h, { row }) => {
              if (row[`costPrice_${tag}`] == null) {
                return <span>{ row[`remark_${tag}`] }</span>
              }
              return <el-input
                size="mini"
                v-model={row[`remark_${tag}`]}
              />
            }
          }
          if (i.prop.includes('costDiffExceedTenRemark')) {
            i.render = (h, { row }) => {
              if (row[`costPrice_${tag}`] == null) {
                return <span>{ row[`costDiffExceedTenRemark_${tag}`] }</span>
              }
              return <el-input
                size="mini"
                v-model={row[`costDiffExceedTenRemark_${tag}`]}
              />
            }
          }
          if (i.prop.includes('noTaxInvoiceApprovalRemark')) {
            i.render = (h, { row }) => {
              if (row[`costPrice_${tag}`] == null) {
                return <span>{ row[`noTaxInvoiceApprovalRemark_${tag}`] }</span>
              }
              return <el-input
                size="mini"
                v-model={row[`noTaxInvoiceApprovalRemark_${tag}`]}
              />
            }
          }
          if (i.prop.includes('factoryDirect')) {
            i.render = (h, { row }) => {
              if (row[`costPrice_${tag}`] == null) {
                return <span>{ row[`factoryDirect_${tag}`] }</span>
              }
              return <el-select
                size='mini'
                class={ 'active' }
                disabled={!row[`factoryDirectCanUpdate_${tag}`] || this.isReinquiry || !row[`canEditBySkuNum_${tag}`]}
                v-model={row[`factoryDirect_${tag}`]}
                onChange={(val) => { this.handleSelectChange({ val, row, tag, prop: 'factoryDirect' }) }}
              >
                {
                  FACTORY_DIRECT_OPTIONS.map(item => {
                    return <el-option
                      key={item.value}
                      value={item.value}
                      label={item.label}
                    />
                  })
                }
              </el-select>
            }
          }
        })
        this.tableInfo.columns.push({
          label: item.supplierName,
          prop: item.supplierCode,
          children
        });
      }
    },
    // 是否厂直操作逻辑
    handleSelectChange ({ val, row, tag, prop }) {
      this.handleBatchFactoryDirect(val, tag)
    },
    // 批量修改厂直接
    handleBatchFactoryDirect (val, tag) {
      this.tableInfo.list.forEach(item => {
        if (item[`costPrice_${tag}`]) {
          item[`factoryDirect_${tag}`] = val;
        }
      })
    },
    // 获取定标详情
    async queryCalibrationInfo () {
      const params = {
        isCompleteWinBill: this.isReject ? '1' : (sessionStorage.isCompleteWinBill || 0),
        sourcingBillId: this.sourcingBillId,
      };
      const res = await queryCalibrationInfoService(
        params,
        state => { this.tableInfo.loading = state }
      )
      if (res) {
        const { skuList, settleTypeStr, settleType, cityCode, afreshBill } = res.data.winBiddingDto;
        this.recordInfo = {
          settleTypeStr,
          settleType,
          cityCode,
          afreshBill
        }
        this.initTableData(skuList);
        if (skuList.some(item => item.skuType == 1 && !item.tempToPotentialApproveStatus)) {
          return this.$confirm('存在线索商品，请先执行潜在商品准入。', '提示', {
            confirmButtonText: '确定',
            type: 'warning',
            showClose: false,
          }).then(() => {
            this.handleSkuAccess()
          }).catch(() => {});
        }
      }
    },
    // 表格勾选结果
    handleSelect (val) {
      this.tableInfo.selection = val;
    },
    // 可编辑项联动（中标金额=中标数量*进价）
    handleRowChange (data) {
      const { prop, row, val } = data;
      const { cityCode } = this.recordInfo;
      const propName = prop.split('_')[0];
      const supplierCode = prop.split('_')[1];
      if (propName == 'skuNum') {
        row[`skuPrice_${supplierCode}`] = toFixedCustomize(row[`costPrice_${supplierCode}`] * val);
        if (!this.isReinquiry) {
          const params = {
            sourcingBillId: this.sourcingBillId,
            supplierCode,
            cityCode,
            skuList: []
          };
          this.tableInfo.list.map(item => {
            console.log(item[`skuNum_${supplierCode}`])
            if (
              item[`skuNum_${supplierCode}`] !== null &&
            item[`skuNum_${supplierCode}`] !== undefined
            ) {
              params.skuList.push({
                skuCode: item.skuCode,
                skuNum: item[`skuNum_${supplierCode}`],
                unitPrice: item[`unitPrice_${supplierCode}`]
              })
            }
          });
          this.computeFactoryDirect(params).then((res) => {
            this.tableInfo.list.forEach(item => {
              if (item[`unitPrice_${supplierCode}`]) {
                item[`factoryDirect_${supplierCode}`] = res
                item[`canEditBySkuNum_${supplierCode}`] = res == 2
              }
            })
          });
        }
      }
    },
    // 格式化提交数据
    formatSubmitData () {
      const submitList = [];
      this.tableInfo.list.forEach(ele => {
        ele.supplierList.forEach(item => {
          const tag = item.supplierCode;
          item.belongDepartmentName = ele[`belongDepartmentName_${tag}`];
          item.costPrice = ele[`costPrice_${tag}`];
          item.skuNum = ele[`skuNum_${tag}`] || 0;
          item.skuPrice = ele[`skuPrice_${tag}`];
          item.totalPrice = ele[`totalPrice_${tag}`];
          item.workableArrivalTime = ele[`workableArrivalTime_${tag}`];
          item.remark = ele[`remark_${tag}`];
          item.costDiffScale = ele[`costDiffScale_${tag}`];
          item.costDiffExceedTenRemark = ele[`costDiffExceedTenRemark_${tag}`];
          item.noTaxInvoiceApprovalRemark = ele[`noTaxInvoiceApprovalRemark_${tag}`];
          // 是否厂家直送
          item.factoryDirect = ele[`factoryDirect_${tag}`];
          item.factoryDirectStr = ele[`factoryDirectStr_${tag}`];
          // 厂直是否可修改
          item.factoryDirectCanUpdate = ele[`factoryDirectCanUpdate_${tag}`];
          // 是否可修改
          item.canEditBySkuNum = ele[`canEditBySkuNum_${tag}`];
        });
        const obj = {}
        Object.keys(ele).forEach(i => {
          if (!i.includes('_')) {
            obj[i] = ele[i]
          }
        })
        submitList.push(obj)
      });
      return submitList;
    },
    // 展示无销售区域商品列表
    showNoSaleAreaTip (skuList) {
      this.tipVisible = true;
      this.noSaleAreaSkuList = skuList;
    },
    // 定标完成 第一步
    async handleCompleteCalibration () {
      const params = {
        sourcingBillId: this.sourcingBillId,
        emergencyOrder: this.emergencyOrder ? 1 : 0,
        calibrateSkuDTOList: this.formatSubmitData()
      };
      console.log(params)
      this.submitDataForAllStep = params;
      const res = await calibrationStep1Service(params, state => { this.submitLoading = state })
      if (res) {
        if (res.data) {
          const { checkType, data, msg } = res.data;
          // 存在无销售区域商品
          if (checkType == 204) {
            this.showNoSaleAreaTip(data)
          } else {
            this.$confirm(`${msg}`, '提示', {
              type: 'warning',
            }).then(() => {
              // 201-线索商品为一物多码商品（确认的话调用指定接口：）
              if (checkType == 201) {
                this.handleUpdateSkuCode()
              }
              // 202-存在线索商品，需转潜在
              if (checkType == 202) {
                this.handleSkuAccess()
              }
              // 203-需完善图文，且存在未完善图文的潜在商品
              if (checkType == 203) {
                this.handleUpdateImgInfo()
              }
            }).catch(() => {})
          }
        } else {
          this.completeCalStepTwo()
        }
      }
    },
    // 定标完成 第二步 判断此次定标是否需要审批
    async completeCalStepTwo () {
      const res = await calibrationStep2Service(this.submitDataForAllStep, state => { this.submitLoading = state })
      if (res) {
        if (res.data) {
          const { checkType, data, msg } = res.data;
          // 成本差异比例超百分之十校验回填表格数据 填写超比例原因
          if (checkType == 204) {
            this.$message.error(msg)
            this.initTableData(data.calibrateSkuDTOList)
          }
          // 提交成功返回供应商列表且存在非推荐供应商中标，填写原因
          if (checkType == 205) {
            console.log('data:', data)
            this.SET_CALIBRATION_STEP_ONE_INFO(data);
            this.notWinSupplierDiaVisible = true;
          }
        } else {
          this.$message.success(res.msg)
          this.backToOrder();
        }
      }
    },
    // 定标完成 第三步
    async completeCalStepThird (supplierList) {
      const params = {
        ...this.submitDataForAllStep,
        supplierList
      }
      const res = await calibrationStep3Service(params, state => { this.submitLoading = state })
      if (res) {
        this.$message.success(res.msg);
        this.backToOrder();
      }
    },
    handleCloseNotWinSupplier () {
      this.notWinSupplierDiaVisible = false;
    },
    // 返回订货首页
    backToOrder () {
      if (this.isDemand) {
        this.$router.push({ name: 'demandOrder', query: { sts: '10' } }); // 询价完成跳转待受理
      } else {
        this.$router.push({ name: 'order', query: { sts: '300' } }); // 定标完成跳转待生成订单
      }
    },
    // 重新报价
    handleBackQuotePage () {
      if (this.isDemand) {
        this.$router.push({ name: 'demandPurchaseDetail' });
      } else {
        this.$router.push({ name: 'purchaseDetail' });
      }
    },
  },
};
</script>
<style lang="less" scoped>
.table-header {
  margin-bottom: 5px;
  /deep/ .el-input {
    width: 220px;
  }
  button {
    margin-right: 10px;
  }
}
.basic-info {
  margin: 10px 0;
  .operating-area {
    .urgent-order {
      display: inline;
      margin-right: 10px;
    }
  }
}
.active {
  border: 1px dashed red;
  border-radius: 4px;
  /deep/ input {
    border: none;
  }
}
</style>
